$(function(){
    obj.init();
});

window.obj = new function(){
    'use strict';
    return {
        dataGrid: null,
        form: null,
        dom: {
            search: null,
            save: null
        },
        init: function () {
            this.dom.search  = $('#bt_list_search');
            this.dom.save    = $('#bt_form_add, #bt_form_edit');

            this.dataGrid = new xhDataGrid($('#List'), 'Appserver/getApplication');
            this.dataGrid.parseToolbar().init().activeBtn(
                $('#bt_list_push'),
                $('#bt_list_del, #bt_list_syn, #bt_list_off_shelf, #bt_list_school_app, #bt_list_history_app, #bt_list_edit_base, #bt_list_edit_version')
            );

            this.form = new xhForm($('#xh_form'));
            this.form.parse().bindRequired(this.dom.save);

            this.listener();
        },
        listener: function () {
            var $this = this;
            $this.dataGrid.onLoadSuccess = function(data){
                $this.dataGrid.clear();
                if (data.rows.length <= 0) return false;
                $this.dataGrid.mergeCells(['appCode', 'name']);
            };
            //查询
            $this.dom.search.click(function(){
                $this.funObj().search();
            });
            xhTool.bindDocKeyDown($this.dom.search);
            //文件上传初始化
            $this.funObj().initFileUpload();
            //列表添加按钮，打开文件上传页面
            $('#bt_list_add').click(function(){
                $('.xh-datagrid').parent().hide();
                $('#xh_form').parent().parent().hide();
                $('#div_file').fadeIn();
            });
            //重置
            $('#bt_form_reset').click(function(){
                $this.form.reset();
            });
            //返回
            $('#bt_upload_back,#bt_form_back').click(function(){
                $('#div_file').hide();
                xhExtra.backToList();
            });
            //有修改权限，双击列表打开列表
            // if($('#bt_form_edit').length > 0){
            //     $this.dataGrid.onDblClickRow = function(rowIndex, rowData){
            //         $.get(baseUrl + 'Appserver/getApplicationInfo/' + rowData.appId, function(data){
            //             if(xhExtra.checkError(data)) return false;
            //             $this.form.reset().fill(data).triggerRequired();
            //             $('#xh_form').parent().parent().show();
            //             xhExtra.forwardToForm(true);
            //         }, 'json');
            //     };
            // }
            //保存
            $this.dom.save.click(function(){
                $this.form.submit(baseUrl + 'Appserver/releaseApplication', {}, function(data){
                    if(xhExtra.checkError(data)) return false;
                    xhExtra.backToList($this.dataGrid);
                });
            });
            //删除
            $('#bt_list_del').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                var appId = $this.dataGrid.getSelectValues('appId');
                if(!appId) return true;
                xhExtra.askChangeStatus('Appserver/delApplication', appId, $this.dataGrid);
            });
            //同步
            $('#bt_list_syn').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                var appId = $this.dataGrid.getSelectValues('appId');
                if(!appId) return true;
                xhExtra.askChangeStatus('Appserver/synApplication', appId, null, '确认发布至生产环境？');
            });
            //推送到盒子
            // $('#bt_list_push').click(function(){
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     xhExtra.askChangeStatus('Server/pushBoxResource/0',
            //         {
            //             url: $this.dataGrid.getSelectValues('url'),
            //             md5: $this.dataGrid.getSelectValues('md5'),
            //             packageName: $this.dataGrid.getSelectValues('packageName'),
            //             versionCode: $this.dataGrid.getSelectValues('versionCode'),
            //             versionName: $this.dataGrid.getSelectValues('versionName')
            //         }
            //     , null, '推送至盒子？');
            // }) ;
            //下架
            $('#bt_list_off_shelf').click(function () {
                if(xhExtra.buttonDisabled($(this))) return false;
                xhExtra.askChangeStatus('Appserver/setApplicationOffShelf', {packageName: $this.dataGrid.getSelectValue('packageName')}, $this.dataGrid, '确认下架？');
            });
            //推送至学校
            $('#bt_list_school_app').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                window.top.xhTop.showModal({
                    title: '选择学校',
                    content: xhTool.getFrameString('School/schoolChoose', {callback: 'obj.funObj().addAppToSchool', single: 'false'}, 500),
                    size: 'lg',
                    button: '确认'
                });
            });
            //历史版本
            $('#bt_list_history_app').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                var appId = $this.dataGrid.getSelectValue('appId');
                if(!appId) return false;
                window.top.xhTop.showModal({
                    title: '历史版本',
                    content: xhTool.getFrameString('Appserver/historyVersion', {appId: appId}, 550),
                    size: 'lg',
                    button: true,
                    backClose: false
                });
            });
            //修改基本信息
            $('#bt_list_edit_base').click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().editAppBase();
            });
            //修改版本信息
            $('#bt_list_edit_version').click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().editAppVersion();
            });
        },
        funObj: function(){
            var $this = this;
            return {
                search: function () {
                    $this.dataGrid.reload({
                        keywords: xhExtra.getValue($('#list_vague'))
                    });
                },
                initFileUpload: function() {
                    $('#file_app').fileinput({
                        language: 'zh', //设置语言
                        uploadUrl: baseUrl + 'Appserver/uploadApplication', //上传的地址
                        allowedFileExtensions: ['apk', 'ipa'],//接收的文件后缀
                        showUpload: true, //是否显示上传按钮
                        showCaption: true,//是否显示标题
                        showPreview: true, //是否显示预览
                        allowedPreviewTypes: null, //允许预览文件类型
                        dropZoneEnabled: true,//是否显示拖拽区域
                        maxFileSize: 0,//单位为kb，如果为0表示不限制文件大小
                        //minFileCount: 1,
                        maxFileCount: 1, //表示允许同时上传的最大文件个数
                        enctype: 'multipart/form-data',
                        validateInitialCount:true,
                        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
                        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
                        dropZoneTitle: '拖拽应用安装包到这里...<br />仅支持apk/ipa文件'
                    }).on('fileuploaded', function(event, data, previewId, index) {
                        data = data.response;
                        if(xhExtra.checkError(data)) return false;
                        $('#div_file').hide();
                        $('#xh_form').parent().parent().show();
                        $this.form.reset().fill(data);
                        xhExtra.forwardToForm(false);
                    });
                },
                addAppToSchool: function(schoolIds, versionCode) {
                    var packageName = $this.dataGrid.getSelectValue('packageName');
                        versionCode = versionCode || $this.dataGrid.getSelectValue('versionCode');
                    if (!packageName || !versionCode || !schoolIds) {
                        window.top.xhTop.showError('缺少参数');
                        return false;
                    }
                    window.top.swal({
                        title: '选择更新方式',
                        text: '版本号:' + versionCode + '，学校数：' + schoolIds.length,
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        confirmButtonText: '确认',
                        allowOutsideClick: true,
                        showCloseButton: true,
                        showLoaderOnConfirm: true,
                        input: 'select',
                        inputOptions: {0: '更新', 1: '上新'},
                        type: 'info',
                        preConfirm: function(operate) {
                            return new Promise(function (resolve, reject) {
                                xhExtra.askChangeStatus('Appserver/addAppToSchool',
                                    {packageName: packageName, versionCode: versionCode, schoolIds: schoolIds, operate: operate},
                                    null,
                                    '确认更新到学校？'
                                );
                            })
                        }
                    }).then(function(isConfirm) {}, function(dismiss) {});
                },
                editAppBase: function () {
                    var appId =  $this.dataGrid.getSelectValue('appId');
                    window.top.xhTop.showModal({
                        title: '基本信息-' + $this.dataGrid.getSelectValue('name'),
                        content: xhTool.getFrameString('appserver/appBase', {appId: appId}, 450),
                        size: 'md',
                        button: '确认',
                        backClose: false
                    });
                },
                editAppVersion: function () {
                    var appId =  $this.dataGrid.getSelectValue('appId');
                    window.top.xhTop.showModal({
                        title: $this.dataGrid.getSelectValue('name') + '-' + $this.dataGrid.getSelectValue('versionName'),
                        content: xhTool.getFrameString(
                            'appserver/appVersion',
                            {
                                appId: appId,
                                versionCode: $this.dataGrid.getSelectValue('versionCode')
                            },
                            300
                        ),
                        size: 'md',
                        button: '确认',
                        backClose: false
                    });
                }
            }
        }
    }
};